package com.lw.leetcode.dp.b;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 368. 最大整除子集
 *
 * @Author liw
 * @Date 2021/6/3 12:40
 * @Version 1.0
 */
public class LargestDivisibleSubset {
    public List<Integer> largestDivisibleSubset(int[] nums) {

        List<Integer> res = new ArrayList<Integer>();
        int length = nums.length;
        if (length == 1) {
            res.add(nums[0]);
            return res;
        }
        Arrays.sort(nums);

        int[] dp = new int[length];
        Arrays.fill(dp, 1);
        int maxSize = 1;
        int maxVal = dp[0];
        for (int i = 1; i < length; i++) {
            int num = nums[i];
            for (int j = 0; j < i; j++) {
                if (num % nums[j] == 0) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            if (dp[i] > maxSize) {
                maxSize = dp[i];
                maxVal = num;
            }
        }
        if (maxSize == 1) {
            res.add(nums[0]);
            return res;
        }

        for (int i = length - 1; i >= 0 && maxSize > 0; i--) {
            if (dp[i] == maxSize && maxVal % nums[i] == 0) {
                res.add(nums[i]);
                maxVal = nums[i];
                maxSize--;
            }
        }
        return res;
    }

}
